import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog.js'
import { request } from '../../request/index.js'
import { requestPayment, showToast } from '../../utils/asyncWx.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    check: false,
    cart: [],
    totalPrice: '',
    communityObj: {},
    userAddress: {},
    index: ''
  },
  //获取是否选中已同意协议
  getCheck(e) {
    this.setData({
      check: e.detail
    })
  },
  //跳转到收货地址页面
  chooseAddress() {
    wx.navigateTo({
      url: '../address/index?goBack=true'
    });

  },
  //提交订单
  async submitOrder() {
    try {
      const token = wx.getStorageSync("token");
      if (!token) {
        wx.navigateTo({
          url: '../login/index'
        });
        return
      }
      //创建订单
      //请求头参数
      const header = { token }
      const { communityObj, userAddress } = this.data
      //请求体参数
      const groupLeader = communityObj.groupLeader
      const address = userAddress.addressId
      const orderRemark = '哈哈'
      const orderPaymentMethod = 1
      const cart = this.data.cart
      let goodsInfoList = []
      cart.forEach(v => goodsInfoList.push({
        goods: v.id,
        number: v.num
      }))
      console.log(this.data.communityObj)
      let orderParams = { groupLeader, address, orderRemark, orderPaymentMethod, goodsInfoList }
      //orderParams = JSON.parse(JSON.stringify(orderParams))
      //orderParams = JSON.stringify(orderParams)
      //console.log(orderParams)
      //发起请求 获取订单编号
      const res = await request({ url: '/order/fresh', method: 'POST', data: orderParams, header })
      const { orderId, paymentResult } = res.data
      console.log(res.data)
      const pay = {
        nonceStr: paymentResult.nonceStr,
        package: paymentResult.packageValue,
        paySign: paymentResult.paySign,
        signType: paymentResult.signType,
        timeStamp: paymentResult.timeStamp
      }
      await requestPayment(pay)

      const res2 = await request({ url: '/order/' + orderId, data: { orderId }, header })
      console.log(res2)

      let newCart = wx.getStorageSync("cart");
      newCart = newCart.filter(v => !v.checked)
      wx.setStorageSync("cart", newCart);

      await showToast({ title: '支付成功' })
      wx.navigateTo({
        url: '../fruit-order/index?type=3'
      });
    } catch (error) {
      await showToast({ title: '支付失败' })
      wx.navigateTo({
        url: '../fruit-order/index?type=2'
      });
      console.log(error)
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取购物车中的数据
    let cart = wx.getStorageSync("cart");
    //获取社区名   团长名  团长地址
    const communityObj = wx.getStorageSync("communityObj");
    cart = cart.filter(v => v.checked)
    //计算总价
    let totalPrice = 0
    cart.forEach(v => {
      totalPrice += v.num * v.price
    })
    totalPrice = this.returnFloat(totalPrice)
    this.setData({
      cart,
      totalPrice,
      communityObj
    })
    //console.log(this.data.cart)

  },
  //获取用户地址
  async getUserAddress() {
    const token = wx.getStorageSync("token");
    const header = { token }
    const res = await request({ url: '/user/address/personalList', header })
    const { index } = this.data
    if (index !== '') {
      this.setData({
        userAddress: res.data[index]
      })
    } else if (res.data.length > 0) {
      const index = res.data.findIndex(v => v.addressDefault === true)
      if (index !== -1) {
        this.setData({
          userAddress: res.data[index]
        })
      } else {
        this.setData({
          userAddress: res.data[0]
        })
      }
    } else {
      this.setData({
        userAddress: ''
      })
    }
  },
  //保留两位小数
  returnFloat(value) {
    var value = Math.round(parseFloat(value) * 100) / 100;
    var xsd = value.toString().split(".");
    if (xsd.length == 1) {
      value = value.toString() + ".00";
      return value;
    }
    if (xsd.length > 1) {
      if (xsd[1].length < 2) {
        value = value.toString() + "0";
      }
      return value;
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getUserAddress()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})